#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/4/15 15:03
# @Author  : Chenmm
# @File    : user.py
# @Software: PyCharm
import json

from sqlalchemy import or_

from app.api import api
from app.models import SysUser, SysDept, SysRole
from flask import Flask, request, g, jsonify, send_file, session, current_app
from flask_login import login_required, login_user, current_user, logout_user
from datetime import datetime
from app import db




# 获取当前登录用户信息
@api.route('/users/me')
@login_required
def getInfo():
    menus = []
    menuTree = []
    menus += [menu for role in current_user.roles for menu in role.menus if role.menus]

    # remove repeat
    new_dict = dict()
    for obj in menus:
        if obj.id not in new_dict:
            new_dict[obj.id] = obj

    for menu in new_dict.values():
        if menu.perm:
            menuTree.append(menu.perm)



    data = {
        'userId': current_user.id,
        'username': current_user.username,
        'nickname': current_user.nickname,
        'avatar': current_user.avatar if current_user.avatar else "/static/images/default_avatar.gif",
        'roles': [role.name for role in current_user.roles],
        'perms': menuTree,
      }

    return jsonify(
      {'code': '00000', 'data': data,
       'msg': '一切ok'})



# 获取用户分页列表
@api.route('/users/page')
@login_required
def getUserPage():
    args = request.args
    pageNum = args.get('pageNum', 1, type=int)  # 页码
    pageSize = args.get('pageSize', 10, type=int) # 每页记录数
    keywords = args.get('keywords', '').strip() # 关键字(用户名/昵称/手机号)
    status = args.get('status', None) # 用户状态
    startTime = args.get('createTime[0]', None) # 开始时间
    endTime = args.get('createTime[1]', None)  # 结束时间
    direction = args.get('direction', 'ASC')  # 排序方式（正序:ASC；反序:DESC）
    deptId = args.get('direction', 0, type=int)  # 部门ID

    # query = SysUser.query

    # 过滤掉超级管理员，不在前端显示
    query = SysUser.query.filter(~SysUser.roles.any(SysRole.id == 1))


    if keywords != '':
        query = query.filter(or_(SysUser.username.contains(keywords), SysUser.nickname.contains(keywords), SysUser.mobile.contains(keywords)))

    if status is not None:
        query = query.filter(SysUser.status==status)

    if startTime is not None and endTime is not None:
        startTime = datetime.strptime(startTime + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        endTime = datetime.strptime(endTime + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
        query = query.filter(SysUser.create_time.between(startTime, endTime))

    if deptId != 0:
        query = query.filter(SysUser.id == deptId)


    if direction == 'ASC':
        query = query.order_by(SysUser.create_time.asc())
    else:
        query = query.order_by(SysUser.create_time.desc())


    pagination = query.paginate(page=pageNum, per_page=pageSize, error_out=False)
    users = pagination.items
    total = pagination.total

    data_list = []
    for user in users:
        user_dict = user.to_pageination_dict()
        if user_dict['dept_id']:
            user_dict['deptName'] = SysDept.query.filter_by(id=user_dict['dept_id']).first().name
        else:
            user_dict['deptName'] = ''
        data_list.append(user_dict)


    data = {
        'list': data_list,
        'total': total

    }
    return jsonify(
        {'code': '00000', 'data': data,
         'msg': '一切ok'})


# 修改用户密码
@api.route('/users/<int:userId>/password/reset', methods=['PUT'])
@login_required
def resetPassword(userId):
    args = request.args
    password = args.get('password', '123456')  # 新密码
    user = SysUser.query.get(userId)
    if user:
        user.password = password
        db.session.commit()
        return jsonify({'code': '00000', 'data': {}, 'msg': '重置密码成功'})

    return jsonify({'code': '400', 'data': {}, 'msg': '重置密码失败'})


# 获取用户表单详情
@api.route('/users/<int:userId>/form')
@login_required
def getFormData(userId):
    user = SysUser.query.get(userId)
    if user is not None:
        return jsonify({
            'code': '00000',
            'data': {
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname,
                "mobile": user.mobile,
                "gender": user.gender,
                "avatar": user.avatar if user.avatar else '/static/images/default_avatar.gif',
                "email": user.email,
                "status": user.status,
                "deptId": user.dept_id,
                "openId": user.openid,
                "roleIds": [role.id for role in user.roles if role.status == 1 and role.is_deleted == 0]
            },
            'msg': '一切ok'
        })
    return jsonify({'code': '400', 'data': {}, 'msg': '获取用户信息失败'})


# 修改用户
@api.route('/users/<int:userId>', methods=['PUT'])
@login_required
def update(userId):
    # 获取请求数据（以json格式提交时）
    data = request.json or {}
    avatar = data.get("avatar", '/static/images/default_avatar.gif')
    deptId = data.get("deptId", '')
    email = data.get("email", '')
    gender = data.get("gender", '')
    mobile = data.get("mobile", '')
    nickname = data.get("nickname", '')
    openId = data.get("openId", '')
    roleIds = data.get("roleIds", None)
    status = data.get("status", 0)

    user = SysUser.query.get(userId)
    if user is not None:
        user.avatar = avatar
        user.dept_id = deptId
        user.email = email
        user.gender = gender
        user.mobile = mobile
        user.nickname = nickname
        user.openid = openId
        if roleIds is not None:
            user.roles = [SysRole.query.filter_by(id=roleid).first() for roleid in roleIds]
        user.status = status
        db.session.commit()
        return jsonify({'code': '00000', 'data': {}, 'msg': "修改用户" + user.username + "成功"})


    return jsonify({'code': '400', 'data': {}, 'msg': '更新用户失败'})



# 新增用户
@api.route('/users', methods=['POST'])
@login_required
def create():
    try:
        # 获取请求数据（以json格式提交时）
        data = request.json or {}
        avatar = data.get("avatar", '/static/images/default_avatar.gif')
        deptId = data.get("deptId", '')
        email = data.get("email", '')
        gender = data.get("gender", 0)
        mobile = data.get("mobile", '')
        nickname = data.get("nickname", '')
        openId = data.get("openId", '')
        roleIds = data.get("roleIds", None)
        status = data.get("status", 0)
        username = data.get("username", None)

        if username is not None:
            user = SysUser(username=username)
            user.avatar = avatar
            user.dept_id = deptId
            user.email = email
            user.gender = gender
            user.mobile = mobile
            user.nickname = nickname
            user.openid = openId
            user.status = status
            if roleIds is not None:
                user.roles = [SysRole.query.filter_by(id=roleid).first() for roleid in roleIds]

            # 默认密码123456
            user.password = '123456'
            db.session.add(user)
            db.session.commit()
            return jsonify({'code': '00000', 'data': {}, 'msg': "新增用户" + username + "成功"})
        return jsonify({'code': '400', 'data': {}, 'msg': "新增用户失败，用户名不能为空"})
    except Exception as e:
        return jsonify({'code': '400', 'data': {}, 'msg': f"新增用户失败：{str(e)}"})



# # 删除用户
# @api.route('/users/<int:userId>', methods=['DELETE'])
# @login_required
# def deleteById(userId):
#     user = SysUser.query.get(userId)
#     if user is not None:
#         db.session.delete(user)
#         db.session.commit()
#         return jsonify({'code': '00000', 'data': {}, 'msg': "删除用户" + user.username + "成功"})
#     return jsonify({'code': '400', 'data': {}, 'msg': "删除用户失败，用户不存在"})


# 删除用户
@api.route('/users/<userIds>', methods=['DELETE'])
@login_required
def deleteByIds(userIds):
    try:
        ids = str(userIds).split(',')
        users = SysUser.query.filter(SysUser.id.in_(ids))
        for user in users:
            db.session.delete(user)
        db.session.commit()
        return jsonify({'code': '00000', 'data': {}, 'msg': "批量删除用户成功"})
    except Exception as e:
        return jsonify({'code': '400', 'data': {}, 'msg': f"批量删除用户失败：{str(e)}"})


# 获取个人中心用户信息
@api.route('/users/profile')
@login_required
def getProfile():
    user = current_user._get_current_object()
    data = {
        "id": user.id,
        "username": user.username,
        "nickname": user.nickname,
        "avatar": user.avatar,
        "gender": user.gender,
        "mobile": user.mobile,
        "email": user.email,
        "deptName": SysDept.query.get(user.dept_id).name,
        "roleNames":  ','.join([role.name for role in user.roles]),
        "createTime": user.create_time.strftime("%Y-%m-%d %H:%M:%S")
    }
    return jsonify({'code': '00000', 'data': data, 'msg': "一切ok"})


# 修改个人中心用户信息
@api.route('/users/profile', methods=["PUT"])
@login_required
def updateProfile():
    # 获取请求数据（以json格式提交时）
    data = request.json or {}
    nickname = data.get("nickname", '')
    id = data.get("id", None)
    gender = data.get("gender", '0')
    if id is not None:
        user = SysUser.query.get(id)
        user.nickname = nickname
        user.gender = gender
        db.session.commit()
        return jsonify({'code': '00000', 'data': {}, 'msg': "修改个人信息成功"})
    else:
        return jsonify({'code': '400', 'data': {}, 'msg': "更新账号资料失败，没有此用户."})


# 获取用户下拉列表
@api.route('/users/options')
@login_required
def getOptions():
    users = SysUser.query.filter_by(status=1, is_deleted=0).all()
    data = [user.to_option_json() for user in users]

    return jsonify(
        {'code': '00000', 'data': data,
         'msg': '一切ok'})


# 修改个人中心用户密码
@api.route('/users/password', methods=["PUT"])
@login_required
def changePassword():
    # 获取请求数据（以json格式提交时）
    data = request.json or {}
    oldPassword = data.get("oldPassword", '')
    confirmPassword = data.get("confirmPassword", '')
    newPassword = data.get("newPassword", '')
    user = current_user._get_current_object()
    if user.verify_password(oldPassword):
        if confirmPassword == newPassword:
            user.password = newPassword
            db.session.commit()
            return jsonify({'code': '00000', 'data': {}, 'msg': "修改密码成功"})
        else:
            return jsonify({'code': '400', 'data': {}, 'msg': "两次新密码不一致."})
    else:
        return jsonify({'code': '400', 'data': {}, 'msg': "修改密码失败，原密码错误."})


    # --TODO LIST

    '''
    
    
  /** 下载用户导入模板 */
  downloadTemplate() {
    return request({
      url: `${USER_BASE_URL}/template`,
      method: "get",
      responseType: "blob",
    });
  },

  /**
   * 导出用户
   *
   * @param queryParams 查询参数
   */
  export(queryParams: UserPageQuery) {
    return request({
      url: `${USER_BASE_URL}/export`,
      method: "get",
      params: queryParams,
      responseType: "blob",
    });
  },

  /**
   * 导入用户
   *
   * @param deptId 部门ID
   * @param file 导入文件
   */
  import(deptId: string, file: File) {
    const formData = new FormData();
    formData.append("file", file);
    return request<any, ExcelResult>({
      url: `${USER_BASE_URL}/import`,
      method: "post",
      params: { deptId: deptId },
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },
  
  /** 发送短信验证码（绑定或更换手机号）*/
  sendMobileCode(mobile: string) {
    return request({
      url: `${USER_BASE_URL}/mobile/code`,
      method: "post",
      params: { mobile: mobile },
    });
  },

  /** 绑定或更换手机号 */
  bindOrChangeMobile(data: MobileUpdateForm) {
    return request({
      url: `${USER_BASE_URL}/mobile`,
      method: "put",
      data: data,
    });
  },

  /** 发送邮箱验证码（绑定或更换邮箱）*/
  sendEmailCode(email: string) {
    return request({
      url: `${USER_BASE_URL}/email/code`,
      method: "post",
      params: { email: email },
    });
  },

  /** 绑定或更换邮箱 */
  bindOrChangeEmail(data: EmailUpdateForm) {
    return request({
      url: `${USER_BASE_URL}/email`,
      method: "put",
      data: data,
    });
  },

    
    '''